/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.component.comboBox;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.BevelBorder;
import javax.swing.plaf.basic.BasicComboPopup;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.WaitComponent;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.factory.UIFactory;
import com.ruipengkj.service.TCommodityService;
/**
 * 进销属性：采购退货
 */
public class CommodityJComboBoxTabelPopupReturn extends BasicComboPopup implements ActionListener,MouseListener,KeyListener,PageDelegale{
	private static final long serialVersionUID = 1L;
	
	private JButton queryButton;//查询按钮
	private JLabelJTextFieldComponent commodityTF; //编号
	private JLabelJTextFieldComponent commodityName; //商品名称
	
	private JTable table = null;
	private JScrollPane tableJsp;
	private BaseCommodityModel tableModel=null;
	private TCommodityService tCommodityService;
	private PagingComponent pagingComponent;//翻页组件
	
	private  DefaultComboBoxModel defaultComboBoxModel =new DefaultComboBoxModel();
	private UIFactory uiFactory;
	private WaitComponent waitComponent;
	private TStore tStore = null;
	
	private int currentPage = 0;//从第几条数据查起
	private int count = 0;//总数
	
	/**
	 * box:JComboBox实例
	 * tableModel:TableModel实例
	 * */
	public CommodityJComboBoxTabelPopupReturn(JComboBox box, TStore tStore) {
		super(box);
		this.tStore = tStore;
		box.setModel(defaultComboBoxModel);
		tCommodityService=BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		uiFactory=UIFactory.getInstance();
		waitComponent=WaitComponent.getInstance();
		this.setLayout(new BorderLayout());
		Dimension dim=new Dimension(500, 300);
		this.setSize(300, 200);
		this.setPreferredSize(dim);
		this.setBackground(Color.WHITE);
		
		table=uiFactory.createRPJTable(tableModel, null, this, 30, JLabel.CENTER);
//		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		
		
		tableJsp=new JScrollPane(table);
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		topPanel();
		this.add(topPanel(),BorderLayout.NORTH);
		this.add(tableJsp,BorderLayout.CENTER);
		this.add(pagingComponent,BorderLayout.SOUTH);
		
		this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
		this.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		
		this.setCursor(Util.CURSOR_DEFAULT);
	}

	private JPanel topPanel(){
		JPanel top_jp = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_1).getImage());
		top_jp.setLayout(new FlowLayout(FlowLayout.LEFT));
		commodityTF=new JLabelJTextFieldComponent("商品编号：", 10);
		commodityName=new JLabelJTextFieldComponent("商品名称：", 10);
		queryButton=new JButton("查询");
		queryButton.addActionListener(this);
		top_jp.add(commodityTF);
		top_jp.add(commodityName);
		top_jp.add(queryButton);
		return top_jp;
	}

	@Override
	protected void firePropertyChange(String propertyName, Object oldValue,Object newValue) {
		if (propertyName.equals("visible")) {
			if (oldValue.equals(Boolean.FALSE)&& newValue.equals(Boolean.TRUE)) { // SHOW
				try {
					 tableModel=new BaseCommodityModel();
					 termQuery();
					 table.setModel(tableModel);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (oldValue.equals(Boolean.TRUE)&& newValue.equals(Boolean.FALSE)) { // HIDE
			}
		}
		super.firePropertyChange(propertyName, oldValue, newValue);
	}

	public void hide(){
		
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource()==table){
			if(e.getClickCount()==2){
				int row=table.getSelectedRow();
				TCommodity comm=tableModel.getTCommodityList().get(row);
				if(comm!=null){
					if (comboBox.isEditable() && comboBox.getEditor() != null) {
						comboBox.configureEditor(comboBox.getEditor(), comm);
					}
					defaultComboBoxModel.addElement(comm);
					comboBox.setSelectedItem(comm);
					super.hide();
				}
				
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	//查询总条数
		private void countQuery(String sql) {
			sql = sql.replace(" o.commodityID, o.price, o.name, o.discountPrice, o.barcode, o.batchPrice, o.unit, o.avgPrice", " count(*) ");
			sql = sql.replace(" limit "+ currentPage + ",15", "");
				
			List<Object[]> objectList = tCommodityService.querySQL(sql);
			if (objectList != null && objectList.size() > 1) {
				this.count = Integer.parseInt(objectList.get(1)[0].toString());
			}
		}
		
		//組裝sql語句
		private String createSql() {
			String sql = ApplicationContext.commodity_sql_buy_reutrn;
			
			String commodityID = commodityTF.getText().getText().trim();
			String commodityName = this.commodityName.getText().getText().trim();
			if (!commodityID.equals("")) {
				sql += " and o.commodityid like '%"+commodityID+"%'";
			}
			if (!commodityName.equals("")) { 
				sql += " and o.name like '%"+commodityName+"%'";
			}
			
			sql += " and store.storeid='"+tStore.getStoreID()+"'";
			
			sql += " limit "+ currentPage + ",15";
			
//			System.out.println(sql);
			return sql;
		}
		
	//条件查询
	private void termQuery(){
		if(tStore != null) {
			tableJsp.getViewport().remove(table);
			tableJsp.getViewport().add(waitComponent);
			tableModel.getTCommodityList().clear();
			try {
				String sql = createSql();
				countQuery(sql);
				
//				System.out.println(sql);
				List<Object[]> objectList =tCommodityService.querySQL(sql);
				
				//添加菜品
				if(objectList!=null){
					for (int i = objectList.size() - 1; i > 0; --i) {
						Object[] objects = objectList.get(i);
						
						TCommodity tCommodity = new TCommodity(
								(String)objects[0],//commodityID
								(Double)objects[1],//price
								(String)objects[2],//name
								(Double)objects[3],//discountPrice
								(String)objects[4],//barcode
								(Double)objects[5],//batchPrice
								(String)objects[6],//unit
								(Double)objects[7]//avgPrice
						);
						tCommodity.setStockNum(ApplicationContext.stockTotalNum(tCommodity.getCommodityID(), null));
						
						tableModel.addList(tCommodity);
					}
					tableJsp.getViewport().remove(waitComponent);
					tableJsp.getViewport().add(table);
					table.updateUI(); 
					pagingComponent.show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==queryButton){
			//查询
			this.termQuery();
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getSource()==commodityTF.getText()||e.getSource()==commodityName.getText()){
			//查询
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				queryButton.doClick();	
			}
		}
	}
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**--------------------------------翻页查询接口------------------------------------*/
	@Override
	public String getInfo() {
		int j = count%15 == 0 ? count/15 : count/15+1;
		
		if (j == 1 && currentPage != 0) {
			homePage();
		}
		
		return "当前第 " + (currentPage/15+1) + " 页/共 "+ j + " 页";
	}

	@Override
	public void homePage() {
		currentPage = 0;
		termQuery();
	}
	
	@Override
	public void lastPage() {
		if (count >= 15) {
			currentPage = count - 15;
		}
		termQuery();
	}

	@Override
	public void nextPage() {
		if (currentPage < count - 15) {
			currentPage += 15;
		}
		termQuery();
	}

	@Override
	public void prevPage() {
		if (currentPage >=15)
			currentPage -= 15;
		else
			currentPage = 0;
		termQuery();
	}

}